import React, {
  useState,
  ReactNode,
  FC,
  Children,
  FunctionComponentElement,
  cloneElement,
} from 'react'
import { MenuItemProps } from './MenuItem'
import {
  MenuProps,
  getMenuClassNames,
  IMenuContext,
  MenuContext,
  allowChildType,
} from './config'

const renderChildren = (children: ReactNode) => {
  return Children.map(children, (child, index) => {
    const childElm = child as FunctionComponentElement<MenuItemProps>
    const { displayName = '' } = childElm.type

    if (allowChildType.includes(displayName)) {
      return cloneElement(childElm, {
        index: childElm.props.index || index + '',
      })
    } else {
      console.error(
        'Warning: Menu has a child which is not a MenuItem component'
      )
    }
  })
}

export const Menu: FC<MenuProps> = props => {
  const {
    style,
    children,
    mode,
    defaultIndex,
    defaultOpenSubMenus,
    onSelect,
  } = props
  const [currentActive, setActive] = useState(defaultIndex)
  const menuClasses = getMenuClassNames(props)

  const handleClick = (index: string) => {
    setActive(index)
    return onSelect && onSelect(index)
  }
  const passedContext: IMenuContext = {
    index: currentActive || '0',
    mode,
    defaultOpenSubMenus,
    onSelect: handleClick,
  }

  return (
    <ul className={menuClasses} style={style} data-testid="test-menu">
      <MenuContext.Provider value={passedContext}>
        {renderChildren(children)}
      </MenuContext.Provider>
    </ul>
  )
}
Menu.defaultProps = {
  defaultIndex: '0',
  mode: 'horizontal',
}

export default Menu
